const express = require('express')
const cors = require('cors')
const app = express()
const jwt = require('jsonwebtoken')
app.use(express.json())
app.use(cors())
const loginData = require('./data/User.json')
const socket = require('socket.io')
const Mock = require('mockjs')
// console.log(data.list);



// 监听端口号
let server = app.listen(3000, () => {
    console.log('端口号为3000,服务启动成功!')
})

let io = socket(server, { cors: true })
// 监听前端事件
io.on('connection', (socketIo) => {
    socketIo.on('postMessage', res => {
        // 模拟学生分布情数据
        const data = Mock.mock({
            'list|5': [
                {
                    "data|13": [
                        {
                            "num|0-1000": 100
                        }
                    ],
                },
            ]
        })
        socketIo.emit('data', data);

        // 间隔3秒发送一次数据,模拟水电用量数据
        const time = setInterval(() => {
            const data2 = Mock.mock({
                'list|4': [
                    {
                        "data|6": [
                            {
                                'num|20000-100000': 20000
                            }
                        ]
                    }
                ]
            })
            socketIo.emit('data2', data2);
            clearInterval(time)
        }, 3000)

        // 模拟校园人员数据
        const time2 = setInterval(() => {
            const data3 = Mock.mock({
                'list|2': [
                    {
                        'data|6': [
                            {
                                'num|10-80': 20
                            }
                        ]
                    }
                ]
            })
            socketIo.emit('data3', data3);
            clearInterval(time2)
        }, 3000)

        // 模拟近三年来毕业人员去向数据
        const time3 = setInterval(() => {
            const data4 = Mock.mock({
                'list|3': [
                    {
                        'data|8': [
                            {
                                'num|2000-6000': 2000
                            }
                        ]
                    }
                ]
            })
            socketIo.emit('data4', data4)
            clearInterval(time3)
        }, 3000)

        // 模拟毕生工作状态
        const time4 = setInterval(() => {
            const data5 = Mock.mock({
                'list|5': [
                    {
                        'data|10-200': 100
                    }
                ]
            })
            socketIo.emit('data5', data5)
            clearInterval(time4)
        }, 3000)

        //毕业生流向城市
        const time5 = setInterval(() => {
            const data6 = Mock.mock({
                'list|7': [
                    {
                        'data|1-11': 10
                    }
                ]
            })
            socketIo.emit('data6', data6)
            clearInterval(time5)
        }, 3000)

    })
});

// 用户登录信息
app.post('/login', (req, res) => {
    let { username, password } = req.body;
    // 账号密码
    let isUser = loginData.some(item => item.username === username && item.password === password);
    // 用户信息
    // let userInfo = loginData.find(item => item.username === username && item.password === password);

    // 判断账号密码是否匹配,并存入token
    if (isUser) {
        let token = jwt.sign({ username, password }, 'tokenKey', { expiresIn: '2h' })
        let refreshToken = jwt.sign({ username, password }, 'refreshTokenKey', { expiresIn: '7d' })
        return res.send({
            code: 1,
            msg: '登录成功',
            token,
            refreshToken,
        })
    } else {
        return res.send({
            code: 0,
            msg: '登录失败,请重新登录'
        })
    }
})

// 中间件
const auth = (req, res, next) => {
    try {
        const data = jwt.verify(req.headers.authorization, 'tokenKey')
        next()
    } catch {
        res.status(401).json({
            code: 0,
            msg: "token失效,身份验证失败"
        })
    }
}

// 获取用户信息成功
app.get('/getUserInfo', auth, (req, res) => {
    res.send({
        code: 1,
        msg: '获取用户信息成功',
    })
})

// 重新获取token
app.get('/refresh', (req, res) => {
    try {
        const { username, password } = jwt.verify(req.query.refreshToken, 'refreshTokenKey')
        let token = jwt.sign({ username, password }, 'tokenKey', { expiresIn: '2h' })
        let refreshToken = jwt.sign({ username, password }, 'refreshTokenKey', { expiresIn: '7d' })
        return res.send({
            token,
            refreshToken,
        })
    } catch {
        res.send({
            msg: 'refreshTokenKey过期',
            code: 0
        })
    }
})